import gradio as gr

from openai import OpenAI

import base64
import io
import PIL
from PIL import Image

client = OpenAI(
    base_url="https://ai.gitee.com/v1",
    api_key="U2NFXWFENR2VPWMIJ7RYPUHV3IBZOXNXAKGUMSOR",
    default_headers={"X-Failover-Enabled": "true", "X-Package": "1910"},
)

#base64转img

def base64_to_image(base64_str):
    base64_data = base64_str.split(',')[1]
    img_bytes = base64.b64decode(base64_data)
    img = PIL.Image.open(io.BytesIO(img_bytes))
    return img


def greet(name):
    response = client.images.generate(
        model="Kolors",
        size="1024x1024",
        extra_body={
            "num_inference_steps": 25,
            "guidance_scale": 7.5,
        },
        prompt=name,
    )
    str = response.data[0].b64_json
    # 将Base64编码的图片数据转换为字节流
    image_bytes = base64.b64decode(str)
    # 将字节流转换为PIL图像对象
    image = Image.open(io.BytesIO(image_bytes))
    return image

output_image = gr.Image()

demo = gr.Interface(fn=greet, inputs="text", outputs=output_image)
demo.launch(server_name='127.0.0.1')